package com.example.handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {


    private final int MSG_ID = 10;

    private TextView textView;

    private MyHandler myHandler = new MyHandler();

    private class MyHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case MSG_ID: {
                    int num = (int) msg.obj;
                    textView.setText("the num is :" + num);
                    break;
                }
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.txt);

        //使用Timer启动一个定时任务
        //delay为long,period为long：从现在起过delay毫秒以后，每隔period
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {

                //生成随机数
                int num = new Random().nextInt(10);

                //定义个消息体
                Message message = new Message();

                //设置消息ID
                message.what = MSG_ID;

                //设置消息内容
                message.obj = num;

                //handler发送消息
                myHandler.sendMessage(message);

            }
        }, 1000, 1000);

    }
}